import { reactive } from "vue";

const store = {
  storage: window.localStorage,
  session: {
    storage: window.sessionStorage,
  },
  bcs: reactive({ list: [] })
};

function serialize(val) {
  return JSON.stringify(val);
}
function deserialize(val) {
  if (typeof val !== "string") {
    return undefined;
  }
  try {
    return JSON.parse(val);
  } catch (e) {
    return val || undefined;
  }
}
const api = {
  set(key, val) {
    if (val === undefined) {
      return this.storage.removeItem(key);
    }
    this.storage.setItem(key, serialize(val));
  },

  get(key, def) {
    let val = deserialize(this.storage.getItem(key));
    return (val === undefined ? def : val);
  },
  has(key) {
    return this.get(key) !== undefined;
  },
  remove(key) {
    this.storage.removeItem(key);
  },

  clear() {
    this.storage.clear();
  },
};

Object.assign(store, api);
Object.assign(store.session, api);


const bcsApi = {
  resetBcs(args) {
    this.bcs.list = [];
    for (let i = 0; i < args.length; i++) {
      let ele = args[i];
      if (typeof ele == "string") {
        this.bcs.list.push({ label: ele, to: undefined });
      } else {
        this.bcs.list.push(ele);
      }
    }
  }
}
Object.assign(store, bcsApi);

export default store;

